<?php
namespace app\payqr\controller;
use app\ApiRest;
use app\payqr\model\CardauthConfig;
use app\card\model\CardExtension;
use app\card\model\CardUserLabel;
use app\Common\model\LongbingTabbar;
use app\payqr\model\CardGoods;
use app\base\model\CardTabBar;
use app\payqr\model\CardCompany;
use app\payqr\model\CardForm;
use app\payqr\model\CardModular;
use app\payqr\model\CardTimeline;
use app\payqr\model\CardTimelineComment;
use app\payqr\model\CardTimelineThumbs;
use app\payqr\model\CardUser;
use app\payqr\model\PayQrConfig;
use app\payqr\model\PayQrRecord;
use app\payqr\model\UserInfo;
use app\payqr\model\UserPhone;
use app\payqr\model\PayqrCarousel;
use app\payqr\model\UserSend;
use app\shop\controller\IndexWxPay;
use app\shop\info\PermissionShop;
use app\shop\model\IndexShopCollage;
use app\shop\model\IndexUserInfo;
use app\validate\ModularMsg;
use think\App;
use app\validate\CardTimelineCommnets;
use think\facade\Cache;
use think\facade\Db;

class Index extends ApiRest
{
    protected $CardModular;
    protected $page;
    protected $list_rows;
    // 继承 验证用户登陆
    public function __construct ( App $app )
    {
        parent::__construct( $app );
        $this->CardModular = new CardModular();
        $this->page = isset( $this->_param[ 'page' ] ) ? $this->_param[ 'page' ] : 1;
        $this->list_rows = isset( $this->_param[ 'list_rows' ] ) ? $this->_param[ 'list_rows' ] : 10;
    }
    public function index()
    {
        $verify = [ 'staff_id' => 'required' ];
        $params = lbGetParamVerify( $this->_param, $verify );
        $carousel = new CardCompany();
        $userinfo = new IndexUserInfo();
        $wherefan=[
          'fans_id' => $params['staff_id']
        ];
        $list = getCache('modular_index');
        //if(!$list){
            $companyid = $userinfo->getCompanyId($wherefan);
            if($this->page ==1){
                $wherecarousel = [
                    'id'=>$companyid
                ];
                $list['carousel'] = $carousel->getImg($wherecarousel);
                $wheres = [
                    'uniacid'=>$this->_uniacid,
                    'status'=>1,
                    'show_top'=>1,
                ];
                $list['model'] = $this->CardModular->list_nopage($wheres);
            }
            $where = [
                'uniacid'=>$this->_uniacid,
                'status'=>1,
                'show'=>1,
            ];
            $list['modular'] = $this->CardModular->listGroup($this->page,$this->list_rows,$where);
            //setCache('modular_index',$list);
        //}
        return $this->success($list);
    }
    public function info(){
        $verify = [ 'id' => 'required'];
        $params = lbGetParamVerify( $this->_param, $verify );
        $where = [
            'status'=>1,
            'uniacid'=>$this->_uniacid,
        ];
        $list = $this->CardModular->listinfo($params[ 'id' ],$this->page,$this->list_rows,$where);
        return $this->success($list);
    }
    public function info_details(){
        $verify = [ 'id' => 'required','modular_id'=>'required','staff_id'=>'required'];
        $params = lbGetParamVerify( $this->_param, $verify );
        $list['list'] = $this->CardModular->infoDetail($params);
        $card_company = new CardCompany();
        $userinfo = new IndexUserInfo();
        $company_id  = $userinfo->getCompanyId(['fans_id'=>$params['staff_id']]);
        //找到公司最上级
        $company_id = $card_company->getUserTopCompanyId($company_id);
        $company = $card_company->getinfo(['uniacid'=>$this->_uniacid,'id'=>$company_id]);
        $list['staff'] = $company;
        return $this->success($list);
    }
    public function message(){
        $data = $this->_input;
        $validate = new ModularMsg();
        $result = $validate->check($data);
        if(!$result){
            return $this->error($validate->getError());
        }
        $from = new CardForm();
        $data['bac1'] = $this->getUserId();
        $data['uniacid'] = $this->_uniacid;
        unset($data['staff_id']);
        $res = $from->createRow($data);
        if ($res === false)
        {
            return $this->error('operation failed');
        }
        return $this->success( [] );
    }
    public function create_timeline(){
        $verify = [ 'content' => 'required','cover' => 'required'];
        $params = lbGetParamVerify( $this->_input, $verify );
        if(!empty($params['cover'])&&is_array($params['cover'])){
            $params['cover'] = implode(',',$params['cover']);
        }
        $user = new UserInfo();
        $user_id = $this->getUserId();
        $user_info = $user->cardList(['fans_id'=>$user_id,'is_staff'=>1]);
        if(!$user_info){
            return $this->error('用户还不是员工');
        }
        $params['uniacid'] = $this->_uniacid;
        $params['user_id'] = $user_id;
        if(mb_strlen($params['content'])>10){
            $params['title'] = mb_substr($params['content'], 0,10);
        }else{
            $params['title'] = $params['content'];
        }
        $timeline = new CardTimeline();
        $res = $timeline->createRow($params);
        if ($res === false)
        {
            return $this->error('operation failed');
        }
        return $this->success( [] );
    }
    //动态
    public function timeline(){
        $staff_id = $this->_param['staff_id'];
        $line = new CardTimeline();
        $userId   = $this->getUserId();
        if($staff_id){
            $userinfo = new IndexUserInfo();
            $company_id  = $userinfo->getCompanyId(['fans_id'=>$staff_id]);
            $where['a.user_id'] = ['in',"$staff_id,$company_id"];
        }else{
            $where['a.user_id'] = $userId;
        }
        $where['a.uniacid'] = $this->_uniacid;
        $where['a.status'] = 1;
        $list = $line->dtlist($this->page,$this->list_rows,$where,$staff_id,$userId);
        $list[ 'data' ] = formatDefaultImage( $list[ 'data' ], 'avatarUrl', 'avatar', $this->defaultImage );
        return $this->success($list);
    }
    public function timeline_details(){
        $verify = [ 'id' => 'required','staff_id' => 'required'];
        $params = lbGetParamVerify( $this->_param, $verify );
        $line = new CardTimeline();
        $where['a.id'] = $params['id'];
        $params['user_id'] = $this->getUserId();
        $info = $line->get_info($where,$params,$this->page,$this->list_rows);
        if(!$info['avatarUrl']){
            $info = formatDefaultImage( $info, 'avatarUrl', 'avatar', $this->defaultImage );
        }
        return $this->success($info);
    }
    //动态删除
    public function timeline_del(){
        $verify = [ 'id' => 'required'];
        $params = lbGetParamVerify( $this->_input, $verify );
         $timeline = new CardTimeline();
        $user = $this->getUserId();
        $user_id = $timeline->getUserid($params['id']);
        if($user !== $user_id){
            return $this->error('不能删除它人的动态');
        }
        $timeline->upsave(['id'=>$params['id']],['status'=>-1]);
        return $this->success([]);
    }
    public function timeline_qr(){
        $data=$this->_input;
        $verify = [ 'id' => 'required','staff_id' => 'required'];
        $params = lbGetParamVerify( $data, $verify );
        $timeline = new CardTimeline();
        $line_id = $timeline->getID($params['id']);
        if(!$line_id){
            return $this->error('动态不存在');
        }
        $params['pid'] = $this->getUserId();
        $params['type'] = 3;
        $rest      = longbingCreateWxCode($this->_uniacid,$params,'pages/info/detail');
        if(isset($rest['qr_path'])) $rest = transImagesOne($rest ,['qr_path'] ,$this->_uniacid);
        $coupon_qr = $rest['qr_path'];
        return $this->success($coupon_qr);
    }
    //点赞
    public function fabulous(){
        $data = $this->_input;
        $validate = new \app\validate\CardTimelineThumbs;
        $result = $validate->check($data);
        if(!$result){
            return $this->error($validate->getError());
        }
        $userId   = $this->getUserId();
        $thumds = new CardTimelineThumbs();
        $timeline = new CardTimeline();
        $line_user_id = $timeline->getUserid($data['timeline_id']);
        if($line_user_id == $userId){
            return $this->error('不能给自己点赞');
        }
        $id  = $thumds->is_fabulous($userId,$data['timeline_id'],$this->_uniacid);
        // 启动事务
        Db::startTrans();
        try {
            if(!$id){
                $data = [
                    'user_id'=>$userId,
                    'timeline_id'=>$data['timeline_id'],
                    'status'=>1,
                    'uniacid'=>$this->_uniacid,
                ];
                 $thumds->createTimelineThumb($data);
                $timeline->where('id',$data['timeline_id'])->inc('thumb')->update();
            }else{
                $thumds->delTimelineThumb($id);
                $timeline->where('id',$data['timeline_id'])->dec('thumb')->update();
            }
            // 提交事务
            Db::commit();
            return $this->success( [] );
        } catch (\Exception $e) {
            // 回滚事务
            //print_r($e->getMessage());exit;
            return $this->error( '数据错误');
        }
    }
    public function comments(){
        $data = $this->_input;
        $validate = new  CardTimelineCommnets();
        $result = $validate->check($data);
        if(!$result){
            return $this->error($validate->getError());
        }
        $comment = new CardTimelineComment();
        $access_token = getAccessToken($this->_uniacid);
        $rest = $comment->wxContentRlue($data['content'],$access_token);
        if($rest['errcode'] != 0){
            return $this->error('内容含有违法违规内容');
        }
        $timeline = new CardTimeline();
        $line_user_id = $timeline->getUserid($data['timeline_id']);
        $userId   = $this->getUserId();
        if($line_user_id == $userId){
            return $this->error('不能给自己的动态评论');
        }
        $data = [
            'timeline_id'=>$data['timeline_id'],
            'user_id'=>$userId,
            'uniacid'=>$this->_uniacid,
            'content'=> $data['content']
        ];
         $comment->createComment($data);
        return $this->success( [] );
    }
    public function code_pay(){
        $verify = [ 'staff_id' => 'required'];
        $params = lbGetParamVerify( $this->_input, $verify );
        //  是否已经授权过手机号
        $user = new UserPhone();
        $user_id = $this->getUserId();
        $phone  = $user->getUserPhone($user_id,$this->_uniacid);
        //  员工信息
        $userInfoModel = new UserInfo();
        $staff = $userInfoModel->cardList(['fans_id' => $params['staff_id'],'is_staff' => 1]);
        if (!$staff)
        {
            return $this->error('未找到员工信息',403);
        }
        //  公司信息
        $companyModel = new CardCompany();
        if ($staff['company_id'])
        {
            $company = $companyModel->getinfo(['id'=>$staff['company_id']]);
            if (!$company)
            {
                $company = $companyModel->getinfo(['uniacid' => $this->_uniacid]);
            }
        }
        else
        {
            $company = $companyModel->getinfo(['uniacid' => $this->_uniacid]);
        }

        $company = $companyModel->changeTopName($company);

        $configModel = new PayqrConfig();
        $config = $configModel->getinfo([ 'uniacid' => $this->_uniacid ]);
        //  没有配置则生成
        if ( !$config ) {
            $configModel->title   = '支付';
            $configModel->uniacid = $this->_uniacid;
            $configModel->save();
            $config = $configModel->getinfo([ 'uniacid' => $this->_uniacid ]);
        }
        $config[ 'is_first' ] = 0;
        //  检查当前用户是否是第一次扫码支付
        $recordModel  = new PayQrRecord();
        $user_id = $this->getUserId();
        $check_record = $recordModel->getinfo([ 'user_id' =>$user_id, 'pay_status' => 1 ]);
        if ( !$check_record ) {
            $config[ 'is_first' ] = 1;
        }
        if (!$config['company_name'] && $company)
        {
            $config['company_name'] = $company['name'];
        }
        if (!$config['company_logo'] && $company)
        {
            $config['company_logo'] = $company['logo'];
        }
        $config['phone'] = '';
        if ($phone)
        {
            $config['phone'] = $phone['phone'];
            $config[ 'is_first' ] = 0;
        }
        return $this->success($config );
    }
    public function payqr(){

       // $verify = ['is_first'=>'required','money'=>'required','staff_id'=>0];

//        $params = lbGetParamVerify( $this->_input, $verify );

        $params = $this->_input;

        $card_user = new CardUser();

        $user_id = $this->getUserId();

        $user = $card_user->getUser(['id'=>$user_id]);

        if(!$user){

            return $this->error('用户信息未找到');
        }
        $user_info = new UserInfo();

        $user_staff = $user_info->cardList(['fans_id'=>$params['staff_id']]);
        if(!$user_staff){
            return $this->error('员工信息未找到');
        }
        $money = $params['money'];
        //  是否是第一次购买
        if ( $params['is_first'] ) {
            $configModel = new PayqrConfig();
            $config = $configModel->getinfo([ 'uniacid' => $this->_uniacid ]);
            if ( $config && $config[ 'first_full' ] && $money >= $config[ 'first_full' ] ) {
                $money = $money - $config[ 'first_reduce' ];
                $money = floatval($money);
                $money = sprintf("%.2f", $money);
            }
        }

        if(!empty($params['text'])&&strlen($params['text'])>600){

            return $this->error('备注过长');
        }
        //  扫码支付订单号
        $out_trade_no = 'p-'.date('Ymd') . uniqid();

        $record = new PayQrRecord();

        $data = [

            'user_id' =>$user_id,

            'staff_id'=>$params['staff_id'],

            'text'    =>!empty($params['text'])?$params['text']:'',

            'money'   =>$money,

            'out_trade_no'=>$out_trade_no,

            'uniacid' =>$this->_uniacid
        ];

        $record->createRow($data);
        $pay_controller = new IndexWxPay($this->app);
        $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$user['openid'],$this->_uniacid,"扫码支付",['type' => 'PayQr' , 'out_trade_no' => $out_trade_no,'is_first'=>$params['is_first'],'money'=>$money],floatval($money));
        return $this->success($jsApiParameters);
    }
    //支付回调
    public function qr_notify($arr,$transaction_id){
        $record = new PayQrRecord();
        $order  = $record->getinfo(['out_trade_no' => $arr['out_trade_no']]);
        if ( !$order || $order[ 'pay_status' ] != 0 ) {
            return false;
        }
        $res = $record->upsave(['id'=>$order['id']],['pay_status'=>1,'transaction_id'=>$transaction_id]);
        if($arr['is_first']){
            $message['content'] = '消费金额'.$arr['money'];
        }else{
            $message['content'] = '消费金额'.$order['money'];
        }
        $message['user_id'] = $order['staff_id'];
        $message['target_id'] = $order['staff_id'];
        $message['uniacid'] = $order['uniacid'];
        $message['create_time'] = time();
        $push_data = array(
            'action'  => 'sendMessageWxServiceNotice',
            'event'   => 'longbingSendMessageWxServiceNotice',
            'message' => $message
        );
        publisher(json_encode($push_data ,true));
        return $res;
    }
    /**
     * @Purpose: 名片-插件-扫码支付-支付成功返回推荐商品
     *
     * @Param: int      $staff   员工id

     * @Return: mixed 查询返回值（结果集对象）
     */
    public function pay_goods ()
    {
        $verify = [ 'staff_id' => 'required'];

        $params = lbGetParamVerify( $this->_input, $verify );

        $goodsModel = new CardGoods();

        $modelExtension = new CardExtension();

        $goods = $modelExtension->cardExtensionList($params['staff_id'], $this->_uniacid);

        if ( !$goods ) {

            $goods = $goodsModel->companyGoodsList($this->_uniacid,$params['staff_id']);

        }
        foreach ($goods as $key=>$val){
            $goods[$key]['is_collage'] = 0;
            $collage_model  = new IndexShopCollage();
            $count          = $collage_model->getCollage(['goods_id' => $val['id'] ,'uniacid' => $this->_uniacid ,'status' => 1]);
            if(!empty($count)) $goods[$key]['is_collage'] = 1;
        }
        //  轮播图
        $carouselModel = new PayqrCarousel();
        $carousel = $carouselModel->onPageLsit(['uniacid' => $this->_uniacid, 'status' => 1]);
        $data = ['goods' => $goods, 'carousel' => $carousel];
        //  支付记录
        $recordModel = new PayQrRecord();
        $user_id = $this->getUserId();
        $record = $recordModel->getinfo(['user_id' => $user_id,'staff_id'=>$params['staff_id'], 'pay_status' => 1]);
        if($record){
            $record['create_time'] = date('Y-m-d H:i',$record['create_time']);
        }
        //  判断是否显示商品

        //实例微信权限类
        $permission = new PermissionShop($this->_uniacid);
        //判断是否有权限
        $auth       = $permission->pAuth();
        //没有权限不返回商品
        if($auth==false){
            $data['goods'] = [];
        }
        $data['record'] = $record;
        return $this->success($data);
    }




    public function user_send(){
        $verify = [ 'label_id_list' => 'required','content' => 'required'];
        $params = lbGetParamVerify( $this->_input, $verify );
        if(is_array($params['label_id_list'])&&count($params['label_id_list'])>0){
            $params['label_id_list'] = trim( implode( ',', $params['label_id_list'] ), ',' );
        }
        $user_label = new CardUserLabel();
        $where = [
            ['label_id','in',$params['label_id_list']],
            ['uniacid','=',$this->_uniacid]
        ];
        $list = $user_label->getlist($where);
        $value['content'] = $params['content'];
        $value['uniacid'] = $this->_uniacid;
        $user_id = $this->getUserId();
        $value['user_id'] = $user_id;
        $value['create_time'] = time();
        if($list){
            foreach($list as $val){
                $value['target_id'] = $val['user_id'];
                $push_data = array(
                    'action'  => 'sendMessageWxServiceNotice',
                    'event'   => 'longbingSendMessageWxServiceNotice',
                    'message' => $value
                );
                publisher(json_encode($push_data ,true));
            }
        }
        $user_send = new UserSend();
        $params['user_id'] = $user_id;
        $params['type'] = 1;
        $params['uniacid'] = $this->_uniacid;;
//        longbingSendMessageWxServiceNotice($value);
        $rest = $user_send->createRow($params);
        if($rest){
            return $this->success([]);
        }else{
            return $this->error('失败');
        }
    }
    public function send_list(){
        $verify = [ 'type' => 'required'];
        $params = lbGetParamVerify( $this->_param, $verify );
        $user_send = new UserSend();
        $where['uniacid'] = $this->_uniacid;
        $where['user_id'] = $this->getUserId();
        $where['type'] = $params['type'];
        $list = $user_send->getlist($where,$this->page,$this->list_rows);
        return $this->success($list);
    }

}
